package me.jessyan.mvparms.demo.mvp.ui.xunfeisdk.xunfei;

import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.support.annotation.Keep;
import android.support.annotation.NonNull;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.TextView;
import android.widget.Toast;


import com.iflytek.cloud.RecognizerListener;
import com.iflytek.cloud.RecognizerResult;
import com.iflytek.cloud.SpeechError;
import com.platform.ai.control.R;


import me.jessyan.mvparms.demo.mvp.ui.xunfeisdk.core.SpeechDialogListener;


/**
 * 讯飞语音识别窗口
 * @Author 35574
 * @Date 2020/7/8
 * @Description
 */
@Keep
public class XunFeiSpeechDialog extends Dialog {
    private static final String TAG = ">>>SpeechDialog";
    private XunFeiRecognizer mXunFeiRecognizer;
    private SpeechDialogListener mListener;
    private TextView mText;
    private boolean callCancelListener = false;
    private boolean autoCancel=true;//自动关闭
    public XunFeiSpeechDialog(@NonNull Context context) {
        super(context, R.style.speech_speechDialogStyle);
        mXunFeiRecognizer = new XunFeiRecognizer(context);
        setCanceledOnTouchOutside(false);
        setCancelable(true);
        setOnCancelListener(new OnCancelListener() {
            @Override
            public void onCancel(DialogInterface dialog) {
                if (callCancelListener && mXunFeiRecognizer != null && mXunFeiRecognizer.isListener()) {
                    mXunFeiRecognizer.cancel();
                    Log.d(TAG, "onCancel:cancel");
                }
            }
        });
    }

    public void setListener(SpeechDialogListener speechDialogListener) {
        mListener = speechDialogListener;
        if (speechDialogListener != null) {
            mXunFeiRecognizer.setRecognizerListener(new RecognizerListener() {
                //2正在说话
                @Override
                public void onVolumeChanged(int volume, byte[] data) {
                    //当前正在说话,音量大小volume
//                    Log.d(TAG, "正在说话：音量:" + volume);
                }

                //1开始语音输入
                @Override
                public void onBeginOfSpeech() {
                    // 此回调表示：sdk内部录音机已经准备好了，用户可以开始语音输入
                    Log.d(TAG, "onBeginOfSpeech:开始语音输入");
                    setText("倾听中");
                }

                //4:结束说话
                @Override
                public void onEndOfSpeech() {
                    // 此回调表示：检测到了语音的尾端点，已经进入识别过程，不再接受语音输入
                    Log.d(TAG, "onEndOfSpeech:结束说话");
                    setText("识别中");
                }

                //3:识别结果
                //5:识别结果
                @Override
                public void onResult(RecognizerResult recognizerResult, boolean b) {
                    //识别结果
                    callCancelListener = false;
                    if(autoCancel){
                        dismiss();
                    }
                    Log.d(TAG, "onResult:识别结果");
                    if (mListener != null) {
                        if (recognizerResult != null) {
                            mListener.onResult(ResultParser.parseResult(recognizerResult.getResultString()));
                        } else {
//                            mListener.onError(new com.heking.speech.core.SpeechError(10000));
                        }
                    }
                }

                //没有检查到网络.(错误码:20001)
                //网络连接发生异常.(错误码:10114)
                @Override
                public void onError(SpeechError speechError) {
                    // 错误码：10118(您没有说话)，可能是录音机权限被禁，需要提示用户打开应用的录音权限。
                    callCancelListener = false;
                    if(autoCancel){
                        dismiss();
                    }
                    String plainDescription = speechError.getPlainDescription(true);
                    Log.e(TAG, "onError:发送错误:" + plainDescription);
                    if (mListener != null) {
//                        mListener.onError(new com.heking.speech.core.SpeechError(speechError.getErrorCode()));
                    }
                }

                @Override
                public void onEvent(int i, int i1, int i2, Bundle bundle) {
                    // 以下代码用于获取与云端的会话id，当业务出错时将会话id提供给技术支持人员，可用于查询会话日志，定位出错原因
                    // 若使用本地能力，会话id为null
                    //	if (SpeechEvent.EVENT_SESSION_ID == eventType) {
                    //		String sid = obj.getString(SpeechEvent.KEY_EVENT_SESSION_ID);
                    //		Log.d(TAG, "session id =" + sid);
                    //	}
//                    Log.d(TAG, "onEvent:");
                }
            });
        } else {
            mXunFeiRecognizer.setRecognizerListener(null);
        }

    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);//必须设置无标题 否则不会匹配内容
        View view = LayoutInflater.from(getContext()).inflate(R.layout.speech_speech_dialog, null);
        mText = (TextView) view.findViewById(R.id.text);
        setContentView(view);

        Window window = getWindow();
        if (window != null) {
            WindowManager.LayoutParams attributes = window.getAttributes();
            attributes.width = WindowManager.LayoutParams.WRAP_CONTENT;
            attributes.height = WindowManager.LayoutParams.WRAP_CONTENT;
            attributes.gravity = Gravity.CENTER;
            window.setAttributes(attributes);
        }
    }

    private void setText(String text) {
        if (mText != null) {
            mText.setText(text);
        }
    }

    public void setAutoCancel(boolean autoCancel) {
        this.autoCancel = autoCancel;
    }

    @Override
    public void show() {
        callCancelListener = true;
        if(mXunFeiRecognizer.startListening()){
            super.show();
        }else{
            Toast.makeText(getContext().getApplicationContext(), "启动语音识别失败", Toast.LENGTH_SHORT).show();
        }
    }

    public void destroy(){
        if(mXunFeiRecognizer!=null){
            mXunFeiRecognizer.destroy();
        }
    }
}
